package com.fqcar.fqdf.core.http;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.HttpHeaderParser;
import com.fqcar.fqdf.entity.ResponseEntity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ResponseEntityOptRequest extends Request<ResponseEntity> {

    private Map<String, String> params = new HashMap<>();
    private final static RetryPolicy mRetryPolicy = new DefaultRetryPolicy(2 * 60 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    private HashMap<String, String> headers = new HashMap<>();
    private final Listener<ResponseEntity> responseEntityListener;

    public ResponseEntityOptRequest(String url) {
        this(url, null);
    }

    public ResponseEntityOptRequest(String url, Listener<ResponseEntity> listener) {
        this(url, null, listener);
    }

    public ResponseEntityOptRequest(String url, Map<String, String> params, Map<String, String> headers) {
        this(url, params, headers, null, null);
    }

    public ResponseEntityOptRequest(String url, Map<String, String> params, Map<String, String> headers, Listener<ResponseEntity> listener) {
        this(url, params, headers, listener, null);
    }

    public ResponseEntityOptRequest(String url, Map<String, String> params, Listener<ResponseEntity> listener) {
        this(url, params, null, listener, null);
    }

    public ResponseEntityOptRequest(String url, Map<String, String> paramsMap, Map<String, String> headersMap,
                                    Listener<ResponseEntity> resultSuccessListener, Response.ErrorListener errorListener) {
        super(Method.POST, url, errorListener);
        if (paramsMap != null) {
            params.putAll(paramsMap);
            removeEmptyParamKeyAndValue(params);
        }
        if (headersMap != null) {
            headers.putAll(headersMap);
            removeEmptyParamKeyAndValue(headers);
        }

        responseEntityListener = resultSuccessListener;
        setShouldCache(false);
        setRetryPolicy(mRetryPolicy);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers;
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return this.params;
    }

    @Override
    protected Response<ResponseEntity> parseNetworkResponse(NetworkResponse response) {

        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            ResponseEntity request = JSON.parseObject(jsonString, ResponseEntity.class);
            return Response.success(request, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(ResponseEntity response) {
        if (responseEntityListener != null) {
            responseEntityListener.onResponse(response);
        }
    }

//    @Override
//    public void deliverError(VolleyError error) {
//        if (this.gofunErrorListener != null) {
//            this.gofunErrorListener.onFailure(new ResponseError(-1000, error.getLocalizedMessage(), false, null));
//        }
//    }

    /**
     * 检查参数是否包含null的key或者value
     *
     * @return
     */
    private void removeEmptyParamKeyAndValue(Map<String, String> originMap) {
        List<String> prepareToRemoveKeys = new ArrayList<>();
        for (Iterator<String> iter = originMap.keySet().iterator(); iter.hasNext(); ) {
            String key = iter.next();
            String value = originMap.get(key);
            if (key == null || value == null) {
                prepareToRemoveKeys.add(key);
            }
        }
        if (!prepareToRemoveKeys.isEmpty()) {
            for (String prepareToRemoveKey : prepareToRemoveKeys) {
                originMap.remove(prepareToRemoveKey);
            }
        }
    }
}